package org.xtown.bingluo.xtieba.ui.activities;

import org.xtown.bingluo.xtieba.R;
import org.xtown.bingluo.xtieba.db.XtiebaAuthorDb;
import org.xtown.bingluo.xtieba.db.XtiebaPostsDb;
import org.xtown.bingluo.xtieba.db.XtiebaPostsInfoDb;
import org.xtown.bingluo.xtieba.model.XtiebaAuthor;
import org.xtown.bingluo.xtieba.model.XtiebaPosts;
import org.xtown.bingluo.xtieba.model.adapters.PostsInfoCursorAdapter;
import org.xtown.bingluo.xtieba.standby.Constants;
import org.xtown.bingluo.xtieba.ui.components.MarqueeText;
import org.xtown.bingluo.xtieba.utils.ApplicationUtils;
import org.xtown.bingluo.xtieba.utils.DateUtils;
import org.xtown.bingluo.xtieba.utils.IOUtils;
import org.xtown.bingluo.xtieba.utils.LogUtlils;
import org.xtown.bingluo.xtieba.utils.StringUtils;
import org.xtown.bingluo.xtieba.utils.UiUtils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.ClipboardManager;
import android.text.InputType;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class PostsInfoActivity extends BaseActivity {
	private enum SwitchUpdateUiCommand {
		INIT, RESET, CHANGE_PAGE, CHANGE_PAGE_CONTENT,
	}

	private static final int FILL_PAGINGLISTVIEWDATA = 110;

	private PostsInfoActivity INSTANCE;
	private ListView lvPosts;
	private Spinner mPageNumSpinner;
	private Button PrePage;
	protected int postsCount;
	protected int currentPageNum = 0;
	private Button NextPage;
	private int currentPosts_id;
	private Cursor mCursor;
	private PostsInfoCursorAdapter mPagingListViewDataCursorAdapter;
	private String currentKzid;
	public static XtiebaPosts currentXtiebaPostsDb = null;
	private ImageView CurrentPosts_Thumbnail;
	private TextView CurrentPosts_KZID;
	private TextView CurrentPosts_Date;
	private TextView CurrentPosts_UpdateDate;
	private TextView CurrentPosts_Title;
	private TextView CurrentPosts_Author;
	private int pageTotalNum;
	private MarqueeText CurrentPosts_Total;
	protected int currentOffet = 0;
	private TextView postsTips;
	private ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		INSTANCE = this;
		setProgressBarVisibility(true);
		setContentView(R.layout.posts_info_activity);
		processExtraData();
		initData();
		buildComponents();
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case FILL_PAGINGLISTVIEWDATA:
				Boolean r = (Boolean) msg.obj;
				updateUI(currentSwitchUpdateUiCommand);
				lvPosts.setVisibility(View.VISIBLE);
				loadingTips.setVisibility(View.GONE);
				break;
			}
		}
	};

	private SwitchUpdateUiCommand currentSwitchUpdateUiCommand;

	private TextView loadingTips;

	protected EditText toOnlineWhatPageEdit;

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		setIntent(intent);// must store the new intent unless getIntent() will
							// return the old one
		LogUtlils.println("---------onNewIntent");
		processExtraData();
	}

	private void processExtraData() {
		Intent intent = getIntent();
		currentKzid = intent.getStringExtra(XtiebaPostsDb.KZID);
		LogUtlils.println("---------currentKzid=" + currentKzid);
	}

	private void initData() {
		currentPosts_id = 0;
		postsCount = 0;
		if (!currentKzid.equals("")) {
			currentXtiebaPostsDb = XtiebaPostsDb.getNetInstance(INSTANCE)
					.selectByKzid(currentKzid);
			if (currentXtiebaPostsDb != null) {
				currentPosts_id = currentXtiebaPostsDb.id;
				postsCount = XtiebaPostsInfoDb.getNetInstance(INSTANCE)
						.getCountByPosts_id(currentPosts_id);
			}
		} else {
			UiUtils.getInstance(INSTANCE).CreateShowToast(
					R.string.PostsInfoActivity_Error, Toast.LENGTH_SHORT);
			finish();
		}
		pageTotalNum = (int) Math
				.ceil((postsCount * 1.0) / Constants.PAGE_SIZE);
	}

	/**
	 * Create main UI.
	 */
	private void buildComponents() {
		CurrentPosts_Thumbnail = (ImageView) findViewById(R.id.CurrentPosts_Thumbnail);
		CurrentPosts_Author = (TextView) findViewById(R.id.CurrentPosts_Author);
		CurrentPosts_Title = (MarqueeText) findViewById(R.id.CurrentPosts_Title);
		CurrentPosts_KZID = (TextView) findViewById(R.id.CurrentPosts_KZID);
		CurrentPosts_Total = (MarqueeText) findViewById(R.id.CurrentPosts_Total);
		CurrentPosts_Date = (TextView) findViewById(R.id.CurrentPosts_Date);
		CurrentPosts_UpdateDate = (TextView) findViewById(R.id.CurrentPosts_UpdateDate);
		CurrentPosts_KZID.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {
				ClipboardManager cbm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
				cbm.setText(CurrentPosts_KZID.getText().toString());
				UiUtils.getInstance(INSTANCE).CreateShowToast(
						R.string.CrawlActivity_Copyed, Toast.LENGTH_SHORT);
				return false;
			}
		});
		CurrentPosts_Title.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View arg0) {
				final Builder builder = new AlertDialog.Builder(INSTANCE).setIcon(
			    R.drawable.icon).setTitle(R.string.Commons_Ask).setMessage(R.string.Commons_WhatFloor).setPositiveButton(R.string.Commons_Ok,
			    new DialogInterface.OnClickListener() {
			     @Override
			     public void onClick(DialogInterface arg0, int arg1) {
			     String pn = toOnlineWhatPageEdit.getText().toString();
		    	 if (StringUtils.isNumeric(pn)) {
		    		 String url = String.format(Constants.ONLINE_URL_TEMPLATE, currentKzid, pn);
		    		 LogUtlils.println("url==="+url);
		    		 if (!ApplicationUtils.openView(INSTANCE, Uri.parse(url), "text/html", "com.android.browser", "com.android.browser.BrowserActivity")) {
		    			 UiUtils.getInstance(INSTANCE).CreateShowToast(
									R.string.Commons_OpenError, Toast.LENGTH_SHORT);
		    		 }
		    	 } else {
		    		 UiUtils.getInstance(INSTANCE).CreateShowToast(
								R.string.Commons_PleaseEnterNumber, Toast.LENGTH_SHORT);
		    	 }
			     }
			    });
				toOnlineWhatPageEdit = new EditText(INSTANCE);
				toOnlineWhatPageEdit.setHint(R.string.Commons_PleaseEnterNumber);
				toOnlineWhatPageEdit.setHintTextColor(R.color.et_text_1);
				toOnlineWhatPageEdit.setInputType(InputType.TYPE_CLASS_NUMBER);
				toOnlineWhatPageEdit.setSingleLine(true);
				String pn = "1";
				if (mCursor != null && mCursor.moveToFirst() != false) {
					pn = String.valueOf(mCursor.getInt(mCursor
							.getColumnIndex(XtiebaPostsInfoDb.FLOOR_NO)));
				}
				toOnlineWhatPageEdit.setText(pn);
				toOnlineWhatPageEdit.selectAll();
				toOnlineWhatPageEdit.setSelected(true);
			    builder.setView(toOnlineWhatPageEdit);
			    builder.show();
				return false;
			}
		});

		postsTips = (TextView) findViewById(R.id.postsTips);
		loadingTips = (TextView) findViewById(R.id.loadingTips);
		lvPosts = (ListView) findViewById(R.id.posts);
		initListView();

		mPageNumSpinner = (Spinner) findViewById(R.id.PageNumSpinner);
		PrePage = (Button) findViewById(R.id.PrePage);
		PrePage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				int postsCountPageNum = pageTotalNum - 1;
				if (currentPageNum == 0) {
					currentPageNum = postsCountPageNum;
				} else {
					currentPageNum--;
				}
				currentOffet = currentPageNum * Constants.PAGE_SIZE;
				getPagingListViewData(currentOffet, Constants.PAGE_SIZE,
						SwitchUpdateUiCommand.CHANGE_PAGE);
			}
		});
		NextPage = (Button) findViewById(R.id.NextPage);
		NextPage.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				int postsCountPageNum = pageTotalNum - 1;
				if (currentPageNum == postsCountPageNum) {
					currentPageNum = 0;
				} else {
					currentPageNum++;
				}
				currentOffet = currentPageNum * Constants.PAGE_SIZE;
				getPagingListViewData(currentOffet, Constants.PAGE_SIZE,
						SwitchUpdateUiCommand.CHANGE_PAGE);
			}
		});
	}

	private void initListView() {

	}

	// updateUI此方法只能在handler中调
	@Override
	protected void updateUI(Object commandObject) {
		SwitchUpdateUiCommand command = (SwitchUpdateUiCommand) commandObject;
		switch (command) {
		case INIT:
			fillCurrentPostsViewData();
			fillPagingListViewData();
			fillPageNumSpinnerData();
			break;
		case RESET:
			break;
		case CHANGE_PAGE:
			mPageNumSpinner.setSelection(currentPageNum);
			mPageNumSpinner.setSelected(false);
			fillPagingListViewData();
			break;
		case CHANGE_PAGE_CONTENT:
			fillPagingListViewData();
			break;
		default:
			break;
		}
	}

	private void fillCurrentPostsViewData() {
		String author = currentXtiebaPostsDb.author;
		XtiebaAuthor o = XtiebaAuthorDb.getNetInstance(INSTANCE).selectByName(
				author);
		String local_avatar = "";
		if (o != null && !o.local_avatar.equals("")) {
			local_avatar = o.local_avatar;
		}
		Bitmap bmp = IOUtils.makeAuthorAvatar(INSTANCE, local_avatar);
		if (bmp != null) {
			CurrentPosts_Thumbnail.setImageBitmap(bmp);
		}
		CurrentPosts_Author.setText(author);
		CurrentPosts_Title.setText(currentXtiebaPostsDb.title);
		// kzid
		CurrentPosts_KZID.setText(currentXtiebaPostsDb.kzid);
		CurrentPosts_Total.setText(postsCount + "");

		// 时间
		CurrentPosts_Date.setText(String.format(
				getString(R.string.PostsCursorAdapter_Publish), DateUtils
						.formatDateForUnixTimestamp(INSTANCE,
								currentXtiebaPostsDb.posts_created_at)));
		CurrentPosts_UpdateDate.setText(String.format(
				getString(R.string.PostsCursorAdapter_CrawlUpdate), DateUtils
						.formatDateForUnixTimestamp(INSTANCE,
								currentXtiebaPostsDb.updated_at)));
	}

	private void getPagingListViewData(final int offet, final int length,
			SwitchUpdateUiCommand command) {
		currentSwitchUpdateUiCommand = command;
		lvPosts.setVisibility(View.GONE);
		loadingTips.setVisibility(View.VISIBLE);
		loadingTips.setText(R.string.loading);
		new Thread() {
			public void run() {
				Boolean r = true;
				mCursor = XtiebaPostsInfoDb.getNetInstance(INSTANCE)
						.getListCursorByPosts_id(currentPosts_id,
								XtiebaPostsInfoDb.POSTS_CREATED_AT, 1, offet,
								length);
				postsCount = XtiebaPostsInfoDb.getNetInstance(INSTANCE)
						.getCountByPosts_id(currentPosts_id);
				pageTotalNum = (int) Math.ceil((postsCount * 1.0)
						/ Constants.PAGE_SIZE);
				Message msg = handler.obtainMessage();
				msg.what = FILL_PAGINGLISTVIEWDATA;
				msg.obj = r;
				handler.sendMessage(msg);
			};
		}.start();
	}

	/**
	 * Fill the list view.
	 */
	private void fillPagingListViewData() {
		startManagingCursor(mCursor);

		String[] from = new String[] { XtiebaPostsInfoDb.CONTENT };
		int[] to = new int[] { R.id.PostsRow_Content };

		mPagingListViewDataCursorAdapter = new PostsInfoCursorAdapter(this,
				R.layout.posts_info_row, mCursor, from, to);
		lvPosts.setAdapter(mPagingListViewDataCursorAdapter);

		setAnimation();
	}

	private void fillPageNumSpinnerData() {
		LogUtlils.println("postsCount==" + postsCount);
		if (postsCount == 0) {
			mPageNumSpinner.setVisibility(View.GONE);
			PrePage.setVisibility(View.GONE);
			NextPage.setVisibility(View.GONE);
			lvPosts.setVisibility(View.GONE);
			postsTips.setText(R.string.postsEmpty);
			LogUtlils.println("postsTips=" + postsTips.getText());
			postsTips.setVisibility(View.VISIBLE);
			return;
		} else {
			mPageNumSpinner.setVisibility(View.VISIBLE);
			PrePage.setVisibility(View.VISIBLE);
			NextPage.setVisibility(View.VISIBLE);
			lvPosts.setVisibility(View.VISIBLE);
			postsTips.setVisibility(View.GONE);
		}

		final String[] pageNums = new String[pageTotalNum];
		for (int i = 0; i < pageTotalNum; i++) {
			pageNums[i] = "第" + (i + 1) + "页";
		}
		// 将可选内容与ArrayAdapter连接
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, pageNums);
		// 设置下拉列表风格
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 将adapter添加到spinner中
		mPageNumSpinner.setAdapter(adapter);
		mPageNumSpinner.setSelection(currentPageNum);
		mPageNumSpinner.setSelected(false);
		// 添加Spinner事件监听
		mPageNumSpinner
				.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						if (mPageNumSpinner.isSelected()) {
							// 设置显示当前选择的项
							arg0.setVisibility(View.VISIBLE);
							currentPageNum = arg2;
							currentOffet = currentPageNum * Constants.PAGE_SIZE;
							getPagingListViewData(currentOffet,
									Constants.PAGE_SIZE,
									SwitchUpdateUiCommand.CHANGE_PAGE_CONTENT);
						}
						mPageNumSpinner.setSelected(true);
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {

					}

				});
	}

	/**
	 * Set the view loading animation.
	 */
	private void setAnimation() {
		AnimationSet set = new AnimationSet(true);

		Animation animation = new AlphaAnimation(0.0f, 1.0f);
		animation.setDuration(600);
		set.addAnimation(animation);

		animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
				-1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
		animation.setDuration(100);
		set.addAnimation(animation);

		LayoutAnimationController controller = new LayoutAnimationController(
				set, 0.5f);
		lvPosts.setLayoutAnimation(controller);
	}

	@Override
	protected void onStart() {
		if (mCursor != null) {
			startManagingCursor(mCursor);
		}
		getPagingListViewData(currentOffet, Constants.PAGE_SIZE,
				SwitchUpdateUiCommand.INIT);
		super.onStart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		// startManagingCursor(mCursor);
		super.onPause();
	}

	@Override
	protected void onStop() {
		if (mProgressDialog != null) {
			mProgressDialog.dismiss();
		}
		stopManagingCursor(mCursor);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		if (mCursor != null) {
			mCursor.close();
		}
		super.onDestroy();
	}

}
